﻿using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class ReceiveGuideEvent: EventNode
    {
        [RequiredField, DelayedField]
        public BBParameter<string> eventName = "EventName";

        public BBParameter<bool> isGuide;
        
        private FlowOutput onReceived;
        private FlowOutput caseTrue;
        private FlowOutput caseFalse;
        
        public override string name {
            get { return  string.Format("➥  [ ReceiveGuideEvent <color=#DDDDDD>{0}</color> ]", eventName); }
        }

        public override void OnPostGraphStarted() {
            Subscribe(graph.agent.gameObject.GetAddComponent<ParadoxNotion.Services.EventRouter>());
        }
        
        public override void OnGraphStoped() {
            var router = graph.agent.gameObject.GetComponent<ParadoxNotion.Services.EventRouter>();
            if ( router != null ) { UnSubscribe(router); }
        }

        protected void Subscribe(ParadoxNotion.Services.EventRouter router) {
            router.onCustomEvent += OnCustomEvent;
        }

        protected void UnSubscribe(ParadoxNotion.Services.EventRouter router) {
            router.onCustomEvent -= OnCustomEvent;
        }
        
        protected override void RegisterPorts()
        {
            onReceived = AddFlowOutput("Received");
            caseTrue = AddFlowOutput("True");
            caseFalse = AddFlowOutput("False");
        }
        
        void OnCustomEvent(string eventName, ParadoxNotion.IEventData msg) {
            if (eventName.Equals(this.eventName.value.Trim(), System.StringComparison.OrdinalIgnoreCase)) 
            {
                //判定是引导ID的，需要直接发送记录
                if (this.isGuide.value)
                {
                    BlueprintUtils.SendGuideRequest(int.Parse(this.eventName.value), 0);
                }
                onReceived.Call(new Flow());
                
                bool recorded = BlueprintUtils.HasBeenRecorded(eventName);
                if (recorded)
                {
                    caseTrue.Call(new Flow());
                }
                else
                {
                    caseFalse.Call(new Flow());
                }
            }
        }
        
    }
}